package com.xxwu.springblogsystem.utils;

import io.jsonwebtoken.*;
import io.jsonwebtoken.io.Encoders;
import io.jsonwebtoken.security.Keys;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.crypto.SecretKey;
import java.security.Key;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
@Slf4j
public class JWTUtils {
    //过期时间
    private static final Long EXPIRATION_TIME = 60 * 60 * 1000L;
    private static final String SECRETSTRING = "/J4QaDh4EjiCitWNJeeWDa68qhzHzRNEkcJUcyaREWM=";
    //对以上签名通过BASE64方式进行编码
    private static final SecretKey KEY = Keys.hmacShaKeyFor(SECRETSTRING.getBytes());


    public static String genJwt(Map<String, Object> claims){
        //构造token
        return Jwts.builder()
                .setClaims(claims)  //自定义内容
                .setExpiration(new Date(System.currentTimeMillis() + EXPIRATION_TIME))  //设置过期时间
                .signWith(KEY)  //签名算法
                .compact();
    }

    //生成签名秘钥
    public void genKey(){
        Key key = Keys.secretKeyFor(SignatureAlgorithm.HS256);
        //通过BASE64编码方式解析后输出
        String secretString = Encoders.BASE64.encode(key.getEncoded());
        System.out.println(secretString);
    }

    //解析令牌
    public static Claims parseJWT(String token){
         //创建解析器设置签名秘钥
        JwtParserBuilder jwtParserBuilder = Jwts.parserBuilder().setSigningKey(KEY);
        //通过解析器对token进行解析
        Claims claims = null;
        try{
            claims = jwtParserBuilder.build().parseClaimsJws(token).getBody();
        } catch (ExpiredJwtException e) {   //超时异常
            log.error("token超时");
            return null;
        }catch (RuntimeException e){
            log.error("claims:{}", claims);
            log.error("token解析失败{}", e.getMessage());
            return null;
        }
        return claims;
    }

    //判定令牌
    public static boolean checkToken(String token){
        Claims body = parseJWT(token);
        if(body == null){
            return false;
        }
        return true;
    }

    //获取令牌中具体内容
    public static Integer getUserIDFromToken(String token){
        Claims body = parseJWT(token);
        if(body != null){
            return (Integer) body.get("userId");
        }
        return null;
    }
}
